package com.aiguigu.lottery.prize.mapper;

import com.aiguigu.lottery.common.entity.PrizeRecordEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface PrizeRecordMapper {
    
    /**
     * 插入中奖记录
     */
    @Insert("INSERT INTO prize_record (user_id, prize_id, prize_name, create_time) " +
            "VALUES (#{userId}, #{prizeId}, #{prizeName}, #{createTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(PrizeRecordEntity record);
    
    /**
     * 根据用户ID查询中奖记录
     */
    @Select("SELECT * FROM prize_record WHERE user_id = #{userId} ORDER BY create_time DESC")
    List<PrizeRecordEntity> findByUserId(@Param("userId") Integer userId);
    
    /**
     * 查询所有中奖记录
     */
    @Select("SELECT * FROM prize_record ORDER BY create_time DESC")
    List<PrizeRecordEntity> findAll();
    
    /**
     * 查询所有中奖记录（包含用户名、手机号和奖品图片）
     */
    @Select("SELECT pr.*, e.username, e.name, e.phone, p.image_url as prizeImage FROM prize_record pr " +
            "LEFT JOIN emp e ON pr.user_id = e.id " +
            "LEFT JOIN prize p ON pr.prize_id = p.id " +
            "ORDER BY pr.create_time DESC")
    List<PrizeRecordEntity> findAllWithDetails();
    
    /**
     * 根据ID查询中奖记录
     */
    @Select("SELECT * FROM prize_record WHERE id = #{id}")
    PrizeRecordEntity findById(@Param("id") Long id);
    
    /**
     * 根据奖品ID删除中奖记录
     */
    @Delete("DELETE FROM prize_record WHERE prize_id = #{prizeId}")
    int deleteByPrizeId(@Param("prizeId") Integer prizeId);
    
    /**
     * 根据ID删除中奖记录
     */
    @Delete("DELETE FROM prize_record WHERE id = #{id}")
    int deleteById(@Param("id") Long id);
    
    /**
     * 根据奖品ID查询中奖记录
     */
    @Select("SELECT * FROM prize_record WHERE prize_id = #{prizeId} ORDER BY create_time DESC")
    List<PrizeRecordEntity> findByPrizeId(@Param("prizeId") Integer prizeId);
    
    /**
     * 根据用户ID查询中奖记录（包含详细信息）
     */
    @Select("SELECT pr.*, e.username, e.name, p.image_url as prizeImage FROM prize_record pr " +
            "LEFT JOIN emp e ON pr.user_id = e.id " +
            "LEFT JOIN prize p ON pr.prize_id = p.id " +
            "WHERE pr.user_id = #{userId} ORDER BY pr.create_time DESC")
    List<PrizeRecordEntity> findByUserIdWithDetails(@Param("userId") Integer userId);
    
    /**
     * 统计用户今日中奖次数
     */
    @Select("SELECT COUNT(*) FROM prize_record WHERE user_id = #{userId} " +
            "AND DATE(create_time) = CURDATE()")
    int countTodayWinsByUserId(@Param("userId") Integer userId);
    
    /**
     * 查询用户最近的中奖记录
     */
    @Select("SELECT pr.*, e.username, p.image_url as prizeImage FROM prize_record pr " +
            "LEFT JOIN emp e ON pr.user_id = e.id " +
            "LEFT JOIN prize p ON pr.prize_id = p.id " +
            "WHERE pr.user_id = #{userId} ORDER BY pr.create_time DESC LIMIT #{limit}")
    List<PrizeRecordEntity> findRecentByUserId(@Param("userId") Integer userId, @Param("limit") Integer limit);
}